package capricornus.utils.shake
{
	import capricornus.core.RefreshManager;
	import capricornus.events.RefreshEvent;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;

	/**
	 * 震动控制器 
	 * @author kael
	 * 
	 */	
	public class ShakeController
	{
		/**
		 * 震动偏移数据 
		 */		
		private static var _arrData:Array;
		/**
		 * 震动对象 
		 */		
		private var _target:DisplayObject;
		
		/**
		 * 是否在震动 
		 */		
		private var _isStart:Boolean = false;
		/**
		 * 当前帧 
		 */		
		private var _currentFrame:int = 0;
		/**
		 * 震动一次的总帧数 
		 */		
		private var _totalFrame:int = 1;
		/**
		 * 震动次数，默认1次 
		 */		
		private var _times:int = 1;
		
		/**
		 * 震动开始时候target的x，y值 
		 */		
		private var _originX:Number;
		private var _originY:Number;
		
		/**
		 * 震动过程中target的x，y值 
		 */		
		private var _shakingX:Number;
		private var _shakingY:Number;
		
		public function ShakeController( target:DisplayObject )
		{
			_target = target;
			init();
		}
		
		private function init():void
		{
			if( _arrData==null ) initData();
		}
		
		private function initData():void
		{
			_arrData = new Array();
			var mc:ShakePanel = new ShakePanel();
			var m:DisplayObject = mc.getChildByName("mc");
			var len:int = mc.totalFrames;
			for( var i:int=1; i<=len; i++ )
			{
				mc.gotoAndStop(i);
				_arrData.push( [int(m.x),int(m.y)] );
			}
			
			_totalFrame = _arrData.length;
		}
		
		/**
		 * 是否在运行 
		 * @return 
		 * 
		 */		
		public function get running():Boolean
		{
			return _isStart;
		}
		
		/**
		 * 开始震动  
		 * @param times 震动次数,默认是1次
		 */			
		public function start( times:int=1 ):void
		{
			_times = times;
			_currentFrame = 0;
			if( !_isStart )
			{
				_originX = _target.x;
				_originY = _target.y;
				_shakingX = _target.x;
				_shakingY = _target.y;
				_isStart = true;
				RefreshManager.instance.addEventListener( RefreshEvent.REFRESH, onRefresh );
			}
		}
		
		/**
		 * 停止震动 
		 */		
		public function stop():void
		{
			if( _isStart )
			{
				_target.x = _originX;
				_target.y = _originY;
				_isStart = false;
				RefreshManager.instance.removeEventListener( RefreshEvent.REFRESH, onRefresh );
			}
		}
		
		private function onRefresh( e:RefreshEvent ):void
		{
			if( _shakingX != _target.x || _shakingY != _target.y )
			{
				//发现不在控制中的target位置变化
				_originX = _target.x;
				_originY = _target.y;
			}
			var arr:Array = _arrData[_currentFrame];
			_target.x = _shakingX = _originX + arr[0];
			_target.y = _shakingY = _originY + arr[1];
			
			_currentFrame++;
			if( _currentFrame >= _totalFrame )
			{
				_currentFrame = 0;
				_times--;
				if( _times < 1 )
				{
					stop();
				}
			}
		}
	}
}















